// HTTP请求封装
class Request {
  constructor() {
    this.baseURL = 'http://localhost:8080';
    this.isRefreshing = false;
    this.requests = [];
  }

  // 请求拦截器
  request(options) {
    return new Promise((resolve, reject) => {
      // 添加token到请求头
      const token = uni.getStorageSync('token');
      if (token) {
        options.header = {
          ...options.header,
          'Authorization': `Bearer ${token}`
        };
      }

      // 发起请求
      uni.request({
        url: this.baseURL + options.url,
        method: options.method || 'GET',
        data: options.data,
        header: options.header,
        success: (response) => {
          // 检查token是否即将过期
          this.checkTokenExpiration(response);
          
          if (response.statusCode === 200) {
            resolve(response.data);
          } else if (response.statusCode === 401) {
            // token过期，尝试刷新
            this.handleTokenExpired(options, resolve, reject);
          } else {
            reject(response);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }

  // 检查token是否即将过期
  checkTokenExpiration(response) {
    const expiringSoon = response.header['X-Token-Expiring-Soon'];
    const expiresAt = response.header['X-Token-Expires-At'];
    
    if (expiringSoon === 'true' && expiresAt) {
      console.warn('Token即将过期，建议刷新');
      // 可以在这里显示提示给用户
      uni.showToast({
        title: '登录状态即将过期，请及时保存数据',
        icon: 'none',
        duration: 3000
      });
    }
  }

  // 处理token过期
  async handleTokenExpired(options, resolve, reject) {
    // 如果正在刷新token，将请求加入队列
    if (this.isRefreshing) {
      this.requests.push({ options, resolve, reject });
      return;
    }

    this.isRefreshing = true;

    try {
      // 尝试刷新token
      const newToken = await this.refreshToken();
      
      if (newToken) {
        // 更新本地存储的token
        uni.setStorageSync('token', newToken);
        
        // 重新发起原始请求
        const token = uni.getStorageSync('token');
        options.header = {
          ...options.header,
          'Authorization': `Bearer ${token}`
        };

        uni.request({
          url: this.baseURL + options.url,
          method: options.method || 'GET',
          data: options.data,
          header: options.header,
          success: (response) => {
            if (response.statusCode === 200) {
              resolve(response.data);
            } else {
              reject(response);
            }
          },
          fail: (error) => {
            reject(error);
          }
        });

        // 处理队列中的请求
        this.requests.forEach(({ options: reqOptions, resolve: reqResolve, reject: reqReject }) => {
          reqOptions.header = {
            ...reqOptions.header,
            'Authorization': `Bearer ${newToken}`
          };
          
          uni.request({
            url: this.baseURL + reqOptions.url,
            method: reqOptions.method || 'GET',
            data: reqOptions.data,
            header: reqOptions.header,
            success: (response) => {
              if (response.statusCode === 200) {
                reqResolve(response.data);
              } else {
                reqReject(response);
              }
            },
            fail: (error) => {
              reqReject(error);
            }
          });
        });
        
        this.requests = [];
      } else {
        // 刷新失败，跳转到登录页
        this.redirectToLogin();
        reject(new Error('Token刷新失败'));
      }
    } catch (error) {
      console.error('Token刷新失败:', error);
      this.redirectToLogin();
      reject(error);
    } finally {
      this.isRefreshing = false;
    }
  }

  // 刷新token
  async refreshToken() {
    try {
      const token = uni.getStorageSync('token');
      if (!token) {
        return null;
      }

      const response = await uni.request({
        url: this.baseURL + '/user/refresh-token',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.statusCode === 200 && response.data.code === 200) {
        return response.data.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error('刷新token失败:', error);
      return null;
    }
  }

  // 跳转到登录页
  redirectToLogin() {
    // 清除本地存储的用户信息
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
    
    // 显示提示
    uni.showModal({
      title: '登录已过期',
      content: '您的登录状态已过期，请重新登录',
      showCancel: false,
      success: () => {
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        });
      }
    });
  }

  // GET请求
  get(url, params = {}) {
    return this.request({
      url: this.buildUrl(url, params),
      method: 'GET'
    });
  }

  // POST请求
  post(url, data = {}) {
    return this.request({
      url,
      method: 'POST',
      data
    });
  }

  // PUT请求
  put(url, data = {}) {
    return this.request({
      url,
      method: 'PUT',
      data
    });
  }

  // DELETE请求
  delete(url) {
    return this.request({
      url,
      method: 'DELETE'
    });
  }

  // 构建带参数的URL - 修复版本
  buildUrl(url, params) {
    if (Object.keys(params).length === 0) {
      return url;
    }
    
    const queryString = Object.keys(params)
      .map(key => {
        const value = params[key];
        // 处理不同类型的参数值
        if (value === null || value === undefined) {
          return '';
        } else if (typeof value === 'object') {
          // 如果是对象，转换为JSON字符串
          return `${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(value))}`;
        } else {
          return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }
      })
      .filter(item => item !== '') // 过滤空值
      .join('&');
    
    return `${url}?${queryString}`;
  }
}

// 创建实例
const request = new Request();

// 导出
export default request;
